﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using S.Common.EditReproductivePresenceStateHelper;
using S.Common.EditWanderStateHelper;
using S.PurchaseAndSales.Api.Application.Command.SheepSaleCommand;
using S.PurchaseAndSales.Domain.Model;
using S.PurchaseAndSales.Infrastructure.Interface.SalesForm;

namespace S.PurchaseAndSales.Api.Application.CommandHandlers.SheepSaleHandler
{
    public class SaleSheepUpdateCommandHandler : IRequestHandler<SaleSheepUpdateCommand, bool>
    {
        private readonly ISheepSaleRepository repository;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;


        public SaleSheepUpdateCommandHandler(ISheepSaleRepository repository,IMapper mapper,IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        }
        
        /// <summary>
        /// 修改羊只销售
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<bool> Handle(SaleSheepUpdateCommand request, CancellationToken cancellationToken)
        {
            string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer "))
            {
                authHeader = authHeader.Substring("Bearer ".Length).Trim();
            }
            string LocalConsul = configuration.GetValue<string>("GetKongaIp");
           
            SheepSaleModel sheepSaleModel = mapper.Map<SheepSaleModel>(request);
            //修改在场状态:
            EditReproductivePresenceState.UpdateReproductivePresenceState(request.EarTag, 2, 3,DateTime.Now, LocalConsul);
            //修改流转状态:
            EditWanderState.EditWander(request.EarTag, 7, LocalConsul);
            return repository.UpdateAsync(sheepSaleModel);
        }

    }
}
